/**
 * 表格筛选面板
 */

import React, { useState, useRef, useMemo } from 'react';
import ReactDOM from 'react-dom';
import { base,getMultiLangByID } from 'nc-lightapp-front';
const { NCButton, NCModal, NCSelect, NCFormControl, NCButtonGroup,NCRadio } = base;
import { isUndefined, getRandom, isFunction, getFilterData } from './utils';
// import getSysFieldid from './getSysFieldid';

require('./filterPanel.less');

const { Header, Title, Body, Footer } = NCModal;
const { NCOption } = NCSelect;

/**
 * 获取列模版的一维结构
 * @param columns 模版结构
 * @param finalFactorList 结果容器
 */
const getFactorList = ({ columns, finalFactorList }) => {
  return columns.reduce((currentValue, column) => {
    // 获取表格列配置
    const { children, visible } = column;
    if (!isUndefined(children)) {
      // 判断和并列的情况
      getFactorList({ columns: children, finalFactorList: currentValue });
    } else {
      visible && currentValue.push(column);
    }
    return currentValue;
  }, finalFactorList);
};

/**
 * 筛选条件录入项组件
 * @param {*} filterFactors 整体的筛选条件
 * @param {*} itemKey 筛选条件录入项组件标识
 * @param {*} filterItemList 筛选条件录入项组件配置参数列表
 * @param {*} setFilterItemList 筛选条件录入项组件标识列表更新方法
 * @param {*} afterFilterItemList 有效的筛选项列表
 * @param {*} factorList 所有项的筛选条件数据集合
 * @param {*} columns 可以被选择的模版项集合
 * @param {*} tableScope 表格实例
 * @param {*} currentTable 表格数据实例
 * @param {*} lang 多语
 */
const FilterItem = ({
  filterFactors: { current },
  itemKey,
  filterItemList,
  setFilterItemList,
  afterFilterItemList,
  factorList,
  columns,
  tableScope,
  currentTable,
  lang,
  setFilterTips,
  handleHideLocation, 
  clearLocationResult,
  enterCallBack
}) => {
  /**
   * 当前筛选项的信息
   */
  const { selectedAttr, selectFcous, inputFocus } = filterItemList[itemKey];
  /**
   * 当前项的筛选条件
   */
  let echoInputValue = '';
  const currentFactor = current[itemKey];
  if (currentFactor) {
    const { factorValue } = currentFactor;
    factorValue && (echoInputValue = factorValue);
  }
  const [inputValue, setInputValue] = useState(echoInputValue);
  const [selectedValue, setSelectedValue] = useState(selectedAttr);

  /**
   * select列字段选择回调
   * @param {*} attr 列的字段
   */
  const handleSelectChange = attr => {
    const { current: afterFilterItemListCurrent } = afterFilterItemList;
    /**
     * 更新select的选项
     */
    filterItemList[itemKey].selectedAttr = attr;
    setSelectedValue(attr);
    current[itemKey].attrcode = attr;
    /**
     * 设置列字段标题的筛选状态
     */
    const filteringList = Object.values(filterItemList).map(
      filterItem => filterItem.selectedAttr
    );
    const filteredList = Object.values(afterFilterItemListCurrent).map(
      afterFilterItem => afterFilterItem.selectedAttr
    );
    columns.forEach(column => {
      const { attrcode } = column;
      if (filteringList.includes(attrcode)) {
        column.filterStatus = 'filtering';
      } else {
        column.filterStatus = '';
      }
      if (filteredList.includes(attrcode)) {
        column.filterStatus = 'filtered';
      }
    });
    /**
     * 更改表格, 更新筛选标识
     */
    tableScope.setState({ evidenceData: currentTable });
    /**
     * 当选择‘请选择’的时候,将当前筛选条件清空,pselect时请选择的意思
     */
    if (attr === 'pselect') {
      Reflect.deleteProperty(current, itemKey);
      return;
    }
    /**
     * 1.如果当前筛选项已经选择了筛选条件, 此时就将当前筛选条件和之前的筛选条件合并
     */
    if (currentFactor) {
      current[itemKey] = { ...currentFactor, ...factorList[attr] };
    } else {
      /**
       * 1.如果当前筛选项没有筛选条件, 此时就将当前筛选条件当作筛选条件
       */
      current[itemKey] = {
        ...factorList[attr],
        factorValue: inputValue,
        itemKey
      };
    }
    handleInputChange(''); //清空查询值
  };

  /**
   * input输入条件内容回调
   * @param {*} value 输入的内容
   */
  const handleInputChange = value => {
    /**
     * 1.如果当前筛选项已经选择了筛选条件, 才给条件添加筛选内容
     */
    if (currentFactor) {
      current[itemKey] = { ...currentFactor, factorValue: value, itemKey };
      /**
       * 更新input的值
       * 更新筛选项的渲染配置的值
       * pselect时请选择的意思
       */
      setInputValue(value);
      setFilterTips(''); //清空查询提示结果
      clearLocationResult(tableScope.state.locationResult); //清空查询结果
    } else if (selectedValue !== 'pselect') {
      /**
       * 1.当前选择的条件不是‘请选择’时, 添加当前项的筛选条件
       */
      current[itemKey] = {
        ...factorList[selectedValue],
        factorValue: value,
        itemKey
      };
      /**
       * 更新input的值
       * 更新筛选项的渲染配置的值
       */
      setInputValue(value);
    }
  };
  /**
   * 删除按钮回调
   */
  const handleDel = () => {
    /**
     * 删除当前项
     */
    Reflect.deleteProperty(filterItemList, itemKey);
    /**
     * 删除当前项的筛选条件
     */
    Reflect.deleteProperty(current, itemKey);
    /**
     * 更新筛选标识
     */
    const { current: afterFilterItemListCurrent } = afterFilterItemList;
    const filteringList = Object.values(filterItemList).map(
      filterItem => filterItem.selectedAttr
    );
    const filteredList = Object.values(afterFilterItemListCurrent).map(
      afterFilterItem => afterFilterItem.selectedAttr
    );
    columns.forEach(column => {
      const { attrcode } = column;
      if (!filteringList.includes(attrcode)) {
        column.filterStatus = '';
      }
      if (filteredList.includes(attrcode)) {
        column.filterStatus = 'filtered';
      }
    });
    /**
     * 更新筛选标识, 和筛选项
     */
    tableScope.setState({ evidenceData: currentTable });
    setFilterItemList({ ...filterItemList });
  };

  return (
    <div className="filter-item-container">
      <div className="select-container">
        <NCSelect
          showClear={false}
          autoFocus={selectFcous}
          value={selectedValue}
          onChange={handleSelectChange}
        >
          {/* 请选择 */}
          {[{ attrcode: 'pselect', label: '请选择' }, ...columns].map(
            column => {
              const { attrcode, label } = column;
              return <NCOption value={attrcode}>{label}</NCOption>;
            }
          )}
        </NCSelect>
      </div>
      <div className="input-container">
        <NCFormControl
          value={inputValue}
          onKeyDown={enterCallBack.bind(tableScope)}
          onChange={handleInputChange}
          maxLength={20}
          autoFocus={inputFocus}
        />
      </div>
      {/* <i className="iconfont nc-theme-icon-font-c icon-shanchu" onClick={handleDel} /> */}
    </div>
  );
};

/**
 * 筛选面板组件
 * @param {*} tableColumns  表格模版信息
 * @param {*} tableScope 表格实例
 * @param {*} FilterPanelCallBack 将打开弹窗的回调传给父级
 * @param {*} tableName 表格名称
 * @param {*} lang 多语
 * @param {*} handleResetCallBack 重置后回调
 * @param {*} handleFilterCallBack 筛选后回调
 * 
 */
const FilterPanel = ({
  tableColumns,
  tableScope,
  // 重置后回调
  handleResetCallBack,
  // 筛选后回调
  handleFilterCallBack,
  // 加个默认值,防止报错, 之后处理一下把这个默认值去掉
  FilterPanelCallBack = {},
  //更新表格列
  updateEvidenceColumns,
  tableName,
  lang,
  handleLocationCallBack,
  defalutRadioVal="1",
  locationResult,
  nctableData
}) => {
  /**
   * FilterPanel的真实dom
   */
  let FilterPanelRef = null;
  /**
   * 保存整体的筛选条件
   */
  const filterFactors = useRef({});
  /**
   * 筛选后回显筛选项配置列表
   */
  const afterFilterItemList = useRef({});
  /**
   * 筛选后回显筛选项的筛选条件列表
   */
  const afterFilterFactors = useRef({});

  /**
   * 筛选条件录入项组件配置参数列表, 通过这个列表渲染录入项组件
   */
  const [filterItemList, setFilterItemList] = useState({});
  /**
   * 模态框的状态, 默认隐藏
   */
  const [panelStatus, setPanelStatus] = useState(false);
  /**
   * 模态框的提示
   */
  const [filterTips, setFilterTips] = useState('');

  /**
   * 将模版处理成一维的
   */
  const columns = useMemo(
    () => getFactorList({ columns: tableColumns, finalFactorList: [] }),
    [tableColumns]
  );
  /**
   * 将模版数据处理,整理为每种类型的的筛选条件
   */
  const factorList = useMemo(
    () => columns.reduce((currentValue, column) => {
      const { attrcode, itemtype, languageMeta, scale, datatype, options, multiple } = column;
      currentValue[attrcode] = { attrcode, itemtype, languageMeta, scale, datatype, options, multiple };
      return currentValue;
    }, {}),
    [columns]
  );

  /**
   * 表格的完整数据
   */
  const {
    state: { evidenceData: currentTable }
  } = tableScope;

  /**
   * 关闭弹窗回调
   * @param isReset 判断是否重置
   * @param newCurrentTable 当表格最新的数据
   * @param handleResetCallBack 重置后的回调
   * @param handleFilterCallBack 筛选后的回调
   */
  const handleHide = ({ isReset = false, newCurrentTable = currentTable, handleResetCallBack, handleFilterCallBack }) => {
    if (isReset === true) {
      // 设置表格筛选图标, 重置时将筛选图标全部清空
      columns.forEach(column => {
        column.filterStatus = '';
      });

    } else {
      /**
       * 设置表格筛选图标, 在正常关闭时, 只将filtering状态的图标清空
       */
      const filteringList = Object.values(filterItemList).map(
        filterItem => filterItem.selectedAttr
      );
      columns.forEach(column => {
        const { attrcode, filterStatus } = column;
        if (filteringList.includes(attrcode)) {
          filterStatus === 'filtering' && (column.filterStatus = '');
        }
      });
    }

    tableScope.setState({ evidenceData: newCurrentTable}, () => {
      // 重置后执行的回调
      if (isReset && isFunction(handleResetCallBack)) {
        handleResetCallBack();
      }
      // 筛选后执行的回调
      if (!isReset && isFunction(handleFilterCallBack)) {
        handleFilterCallBack();
      }
      /**
           * 清空筛选项
           */
      setFilterItemList({});
      /**
       * 清空筛选条件
       */
      filterFactors.current = {};
      /**
       * 清空提示信息
       */
      filterTips.length && setFilterTips('');
       /**
       *更新列(筛选图标),凭证特殊处理
       */
      if(isFunction(updateEvidenceColumns)){
        updateEvidenceColumns()
      }
      // 这里更新状态的顺序会导致  弹窗可能不能正确销毁
      setTimeout(() => {
        /**
         * 关闭弹窗
         */
        setPanelStatus(false);
      }, 20);

    });
  };

  /**
   * 筛选按钮回调
   * @filterFactor 筛选条件 用于在卡片返回列表时重新筛选使用
   * @filterResultItem 是筛选结果项
   */
  const handleFilter = (filterFactor, filterResultItem,preOrNext) => {
    const {
      filterAllData,
      filterCustomColData,
      state: {
        // evidenceData: { rows: currentTableRows_new },
        // mydata:currentTableRows_new,
        evidenceData,//凭证
        mydata,//期初余额
        locationResult
      }
    } = tableScope;
    let  currentTableRows_new=[];
    if(evidenceData){
      currentTableRows_new=evidenceData.rows;
    }
    // 如果传入筛选条件,那就使用传入的
    let currentTableRows=nctableData?nctableData:currentTableRows_new;
    filterFactor && (filterFactors.current = filterFactor);
    filterFactor && (afterFilterFactors.current = filterFactor);
    filterResultItem && (afterFilterItemList.current = filterResultItem);
    const { current: filterFactorsCurrent } = filterFactors;
    const { current: afterFilterItemListCurrent } = afterFilterItemList;
    const { current: afterFilterFactorsCurrent } = afterFilterFactors;
    /**
     * 存储筛选时表格的全数据,这个数据会随时更新
     */
    !filterAllData && (tableScope.filterAllData = [].concat(currentTableRows || []));
    /**
     * 筛选并更新表格显示数据
     */
    const { filterResult: rows, filteredAttrList,locationResultBack } = getFilterData.call(
      tableScope,
      {
        // 筛选原数据, 去除筛选api可能添加的flterindex
        allRows: tableScope.filterAllData.map((row) => {
          if (row.flterIndex) {
            delete row.flterIndex;
          }
          return row;
        }),
        // 筛选条件
        filterFactor: Object.values(filterFactorsCurrent),
        // 自定义列传入数据
        filterCustomColData,
        preOrNext,
        locationResultBack:locationResult
      });
    if (rows.length) {
      /**
       * 1.存储有效的筛选项和筛选条件列表
       */
      const {
        newAfterFilterItemListCurrent,
        newAfterFilterFactorsCurrent
      } = filteredAttrList.reduce(
        (currentValue, attr) => {
          const {
            newAfterFilterItemListCurrent,
            newAfterFilterFactorsCurrent
          } = currentValue;
          if (afterFilterItemListCurrent[attr]) {
            newAfterFilterItemListCurrent[attr] =
              afterFilterItemListCurrent[attr];
            newAfterFilterFactorsCurrent[attr] =
              afterFilterFactorsCurrent[attr];
          } else {
            newAfterFilterItemListCurrent[attr] = filterItemList[attr];
            newAfterFilterFactorsCurrent[attr] = filterFactorsCurrent[attr];
          }
          return currentValue;
        },
        { newAfterFilterFactorsCurrent: {}, newAfterFilterItemListCurrent: {} }
      );
      afterFilterItemList.current = newAfterFilterItemListCurrent;
      afterFilterFactors.current = newAfterFilterFactorsCurrent;
      /**
       * 设置表格筛选图标
       */
      const filteringList = Object.values(filterItemList).map(
        filterItem => filterItem.selectedAttr
      );
      const filteredList = Object.values(newAfterFilterItemListCurrent).map(
        afterFilterItem => afterFilterItem.selectedAttr
      );
      columns.forEach(column => {
        const { attrcode } = column;
        if (filteredList.includes(attrcode)) {
          column.filterStatus = 'filtered';
        } else if (!filteringList.includes(attrcode)) {
          column.filterStatus = '';
        }
      });
      /**
       * 1.关闭弹框
       */
      // 处理筛选后的勾选逻辑, 还差亚军加的那种禁用感叹号的情况没有处理, 重置后和筛选后添加一个回调函数, 继梦的参数加上, 在模版上
      // currentTable.checkedAll = rows.every(item => !!item.selected);
      // currentTable.indeterminate = rows.some(item => !!item.selected);
      // // 处理筛选后的多选框禁用逻辑
      // currentTable.disabledAll = rows.every(item => !!item.disabled);
      let resultStr=`结果：${Number(locationResultBack.activeIndex)+1}/${locationResultBack.currentIndex.length}`;
      setFilterTips(resultStr);
      locationResultBack.locationFlag=true;
      handleLocationCallBack(locationResultBack);
      // handleHide({ newCurrentTable: { ...currentTable, rows }, handleFilterCallBack });
    } else {
      // '没有找到，换个词试一试'
      if (locationResultBack.searchValue) {
        setFilterTips(lang['publiccomponents-000155']?lang['publiccomponents-000155']:getMultiLangByID('publiccomponents-000155'));
      } else {
        if (locationResultBack) {
          locationResultBack.searchValue = '';
          locationResultBack.activeIndex='';
          locationResultBack.current_Index='';
          locationResultBack.locationFlag=false;
        }
        setFilterTips('');
        handleHideLocation(false, locationResultBack, () => {
          handleLocationCallBack(locationResultBack);
        })
      }
    }

  };
const clearLocationResult = (locationResultBack) => {
  locationResultBack.searchValue='';
  locationResultBack.activeIndex='';
  locationResultBack.currentIndex=[];
  locationResultBack.current_Index='';
  locationResultBack.locationFlag=false;
  locationResultBack.isFirst = true;
  locationResultBack.isLast = true;
}
const handleHideLocation=(isHide=true,locationResultBack,callback)=>{
  if(isFunction(callback)){
    callback();
  }else{
    if(locationResultBack && locationResultBack.searchValue){
      locationResultBack.searchValue='';
      locationResultBack.activeIndex='';
      locationResultBack.currentIndex=[];
      if(!isHide){
        locationResultBack.current_Index='';
      }
      locationResultBack.locationFlag=false;
      locationResultBack.isFirst = true;
      locationResultBack.isLast = true;
      handleLocationCallBack(locationResultBack);
    }
  }
  if(isHide){
        /**
     * 清空存储的筛选状态下表格的完整数据
     */
    tableScope.filterAllData = null;
    /**
     * 清空筛选后回显筛选项配置列表
     */
    afterFilterItemList.current = {};
    /**
     * 清空筛选后回显筛选项的筛选条件列表
     */
    afterFilterFactors.current = {};
    filterFactors.current = {};
    setFilterItemList({});
    setFilterTips('');
    setTimeout(() => {
        /**
         * 关闭弹窗
         */
        setPanelStatus(false);
      }, 20);
    }
  }
  /**
   * enter执行筛选的快捷键
   */
  const enterCallBack = e => {
    if (e && e.keyCode == 13) {
      // enter 键
      handleFilter();
    }
  };

  /**
   * 模态框打开结束时回调
   */
  const handleEntered = () => {
    // FilterPanelRef.childNodes[1]
    //   .querySelector('.modal-content-parent')
    //   .addEventListener('keydown', enterCallBack);
    setFilterItemList({ ...filterItemList });
  };

  /**
   * 模态框关闭结束时回调
   */
  const handleExited = () => {
    // FilterPanelRef.childNodes[1]
    //   .querySelector('.modal-content-parent')
    //   .removeEventListener('keydown', enterCallBack);
  };

  /**
   * 添加按钮回调
   */
  const handleAdd = () => {
    /**
     * 新增筛选条件录入项组件的标识, 新增筛选项
     */
    let key = getRandom();
    Object.values(filterItemList).forEach(filterItem => {
      filterItem.selectFcous = false;
      filterItem.inputFocus = false;
    });
    filterItemList[key] = {
      key,
      selectedAttr: 'pselect',
      selectFcous: true,
      inputFocus: false
    };
    setFilterItemList({ ...filterItemList });
  };

  /**
   * 清空按钮回调
   */
  const handleClear = () => {
    /**
     * 1.清空筛选项
     */
    let key = getRandom();
    setFilterItemList({
      [key]: {
        key,
        selectedAttr: 'pselect',
        selectFcous: true,
        inputFocus: false
      }
    });
    /**
     * 1.清空筛选条件
     */
    filterFactors.current = {};
    /**
     * 设置表格筛选图标
     */
    const filteringList = Object.values(filterItemList).map(
      filterItem => filterItem.selectedAttr
    );
    columns.forEach(column => {
      const { attrcode } = column;
      if (filteringList.includes(attrcode)) {
        column.filterStatus === 'filtering' && (column.filterStatus = '');
      }
    });
    tableScope.setState({ evidenceData: currentTable });
  };

  /**
   * 清空表格筛选的标识
   */
  const handleClearFliterStatus = () => {
    columns.forEach(column => {
      column.filterStatus = '';
    });
    tableScope.filterAllData = null;
    afterFilterItemList.current = {};
    afterFilterFactors.current = {};
  };

  /**
   * 当调用筛选api时, 将当前筛选功能的标识清空并更新表格最新的各种状态
   * @param rows 调用筛选api时, 得到的结果
   * @param isClearfilterAllData 是否重置数据, 清空filterAllData, 退出筛选状态, 恢复为正常状态
   */
  const handleResetFliterStatus = ({ rows, isClearfilterAllData = false }) => {
    // 清空表格筛选的标识
    columns.forEach(column => {
      column.filterStatus = '';
    });
    // 清空filterAllData, 恢复正常
    isClearfilterAllData && (tableScope.filterAllData = null);
    // 处理重置后的勾选逻辑
    currentTable.checkedAll = !!rows.length && rows.every(item => !!item.selected);
    currentTable.indeterminate = rows.some(item => !!item.selected);
    // 处理重置后的多选框禁用逻辑
    currentTable.disabledAll = !!rows.length && rows.every(item => !!item.disabled);
    /**
     * 清空筛选后回显筛选项配置列表
     */
    afterFilterItemList.current = {};
    /**
     * 清空筛选后回显筛选项的筛选条件列表
     */
    afterFilterFactors.current = {};
  };

  /**
   * 重置按钮回调
   */
  const handleReset = () => {
    const {
      filterAllData,
      state: {
        // evidenceData: { rows: currentTableRows }
        evidenceData,//凭证
        mydata,//期初余额
        locationResult
      }
    } = tableScope;
    // 获取表格全数据
    let  currentTableRows_new=[];
    if(evidenceData){
      currentTableRows_new=evidenceData.rows;
    }
    // 如果传入筛选条件,那就使用传入的
    let currentTableRows=nctableData?nctableData:currentTableRows_new;
    let allRows = filterAllData || currentTableRows;
    // 去除筛选api可能添加的flterindex
    allRows = allRows.map((row, index) => {
      if (row.flterIndex) {
        delete row.flterIndex;
      }
      return row;
    });
    // 处理重置后的勾选逻辑
    currentTable.checkedAll = allRows.every(item => !!item.selected);
    currentTable.indeterminate = allRows.some(item => !!item.selected);
    // 处理重置后的多选框禁用逻辑
    currentTable.disabledAll = allRows.every(item => !!item.disabled);
    /**
     * 将数据恢复为全数据
     * 修正rows  把删除项永远放在最后 （为了保证渲染层与数据层 index的同一性）
     */
    currentTable.rows = allRows;
    /**
     * 清空存储的筛选状态下表格的完整数据
     */
    tableScope.filterAllData = null;
    /**
     * 清空筛选后回显筛选项配置列表
     */
    afterFilterItemList.current = {};
    /**
     * 清空筛选后回显筛选项的筛选条件列表
     */
    afterFilterFactors.current = {};
    /**
     * 关闭弹窗
     */
    handleHide({ isReset: true, handleResetCallBack });
  };

  /**
   * CrtlF打开弹窗回调
   */
  const handleCrtlFOpen = () => {
    let finalFilterItemList = null;
    let { current: afterFilterFactorsCurrent } = afterFilterFactors;
    let { current: afterFilterItemListCurrent } = afterFilterItemList;

    if (Object.keys(afterFilterItemListCurrent).length) {
      /**
       * 渲染缓存的有效的筛选项和筛选条件
       */
      filterFactors.current = afterFilterFactorsCurrent;
      finalFilterItemList = afterFilterItemListCurrent;
      setFilterItemList(finalFilterItemList);
    } else {
      /**
       * 当没有有效的筛选项和筛选条件时
       */
      let key = getRandom();
      Object.values(filterItemList).forEach(filterItem => {
        filterItem.selectFcous = false;
        filterItem.inputFocus = false;
      });
      filterItemList[key] = {
        key,
        selectedAttr: 'pselect',
        selectFcous: true,
        inputFocus: false
      };
    }
    /**
     * 打开弹窗
     */
    setPanelStatus(true);
  };

  /**
   * 点击表头打开弹窗回调
   * 这里包含三种情况, 
   * 1.直接点击表头,弹出筛选框增一个筛选条件
   * 2.筛选成功点击成功图标,重新筛选, 如果只筛选了一项那个进行重置
   * 3.筛选成功, 点击表头其他区域, 弹出筛选框
   * 
   * @param selectedAttr 当前列
   * @param filterStatus 筛选状态
   */
  const handleHeaderOpen = ({ selectedAttr, filterStatus }) => {
    let key = getRandom();
    let finalFilterItemList = null;
    let { current: filterFactorsCurrent } = filterFactors;
    let { current: afterFilterFactorsCurrent } = afterFilterFactors;
    let { current: afterFilterItemListCurrent } = afterFilterItemList;
    if (Object.keys(afterFilterItemListCurrent).length) {
      /**
       * 已经筛选过的情况下, 点击表头不点击筛选图标, 只是弹出筛选框,
       * 并且保存原有筛选项, 不增加筛选项
       */
      if (filterStatus === 'filtered') {
        handleCrtlFOpen();
        return;
      }
      /**
       * 具有有效的筛选项, 已经筛选出结果
       */
      const allocationSelectedAttrs = Object.values(
        afterFilterItemListCurrent
      ).filter(filterItem => {
        filterItem.selectFcous = false;
        filterItem.inputFocus = false;
        return filterItem.selectedAttr === selectedAttr;
      });

      if (allocationSelectedAttrs.length) {
        /**
         * 当前点击列,为有效的筛选项, 将当前项筛选条件去掉重新筛选,
         * 如果去掉当前筛选条件后没有了筛选条件,执行重置操作
         */
        allocationSelectedAttrs.forEach(filterItem => {
          const { key } = filterItem;
          Reflect.deleteProperty(filterItemList, key);
          Reflect.deleteProperty(filterFactorsCurrent, key);
          Reflect.deleteProperty(afterFilterFactorsCurrent, key);
          Reflect.deleteProperty(afterFilterItemListCurrent, key);
        });
        filterFactors.current = afterFilterFactorsCurrent;
        finalFilterItemList = afterFilterItemListCurrent;
        if (Object.values(afterFilterItemListCurrent).length) {
          // 再次进行筛选
          handleFilter();
          return;
        } else {
          // 进行重置
          handleReset();
          return;
        }
      } else {
        /**
         * 当前点击列,不是有效的筛选项, 增加一个空筛选项
         */
        filterFactors.current = afterFilterFactorsCurrent;
        finalFilterItemList = {
          ...afterFilterItemListCurrent,
          [key]: {
            key,
            selectedAttr,
            selectFcous: false,
            inputFocus: true
          }
        };
        /**
         * 设置表格筛选图标
         */
        columns.forEach(column => {
          const { attrcode } = column;
          if (selectedAttr === attrcode) {
            // 解决  多页签情况下  列缓存被清除的问题
            column.filterStatus = column.filterStatus || 'filtering';
          }
        });
        tableScope.setState({ evidenceData: currentTable });
      }
      setFilterItemList({ ...finalFilterItemList });
    } else {
      /**
       * 没有有有效的筛选项, 没有筛选出结果, 增加一个空筛选项
       */
      Object.values(filterItemList).forEach(filterItem => {
        filterItem.selectFcous = false;
        filterItem.inputFocus = false;
      });
      filterItemList[key] = {
        key,
        selectedAttr,
        selectFcous: false,
        inputFocus: true
      };
      /**
       * 设置表格筛选图标
       */
      columns.forEach(column => {
        const { attrcode } = column;
        if (selectedAttr === attrcode) {
          // 解决  多页签情况下  列缓存被清除的问题
          column.filterStatus = column.filterStatus || 'filtering';
        }
      });
      tableScope.setState({ evidenceData: currentTable });
      /**
       *更新列(筛选图标),凭证特殊处理
       */
      if (isFunction(updateEvidenceColumns)) {
        updateEvidenceColumns();
      }
    }
    /**
     * 1.打开弹窗
     */
    setPanelStatus(true);
  };

  // 给筛选按钮事件, 设置默认值, 解决报错
  const handleFilterClick = handleFilter.bind(null, null, null);



  /**
   * 将打开弹窗的回调传给父级
   */
  FilterPanelCallBack.current = {
    handleHeaderOpen,
    handleCrtlFOpen,
    handleClearFliterStatus,
    // 当调用筛选api时, 将当前筛选功能的标识清空并更新表格最新的各种状态
    handleResetFliterStatus,
    // 已经进行了筛选的筛选条件
    afterFilterFactors,
    // 已经筛选项
    afterFilterItemList,
    // 筛选api
    handleFilter,
    //重置
    handleReset,
  };
  //选择过滤还是定位
  const RadioRender=({defalutRadio='1'})=>{
    const [radioValue, setRadioValue] = useState(defalutRadio);
    function RadioHandleChange(v){
      setRadioValue(v);
    }
    return(
      <NCRadio.NCRadioGroup
        name="fruit"
        selectedValue={radioValue}
        onChange={RadioHandleChange.bind(this)}>

          <NCRadio value="0" >过滤</NCRadio>

          <NCRadio value="1" >定位</NCRadio>

      </NCRadio.NCRadioGroup>
    )
  }
  const handLocationClickPre=handleFilter.bind(null, null, null,'pre');
  const handLocationClickNext=handleFilter.bind(null, null, null,'next');
  return (
    <NCModal
      ref={dom => {
        FilterPanelRef = ReactDOM.findDOMNode(dom);
      }}
      size="lg"
      zIndex={800}
      show={panelStatus}
      // backdrop={true} //是否展示遮罩层
      onHide={defalutRadioVal=="1"?handleHideLocation.bind(null,true,locationResult):handleHide.bind(null, {})}
      // backdropClosable={true}
      onEntered={handleEntered}
      onExited={handleExited}
      draggable={true}
      resizable={false}
      className="User-Defined filterPanel-modal"
      fieldid="filterPanel"
    >
      <Header closeButton>
        <Title fieldid={`${lang['publiccomponents-000152']?lang['publiccomponents-000152']:getMultiLangByID('publiccomponents-000152')}${tableName || ''}`}>
          {defalutRadioVal=="1"?
          `${lang['publiccomponents-000159']?lang['publiccomponents-000159']:getMultiLangByID('publiccomponents-000159')}`
          :
          `${lang['publiccomponents-000152']?lang['publiccomponents-000152']:getMultiLangByID('publiccomponents-000152')}${tableName || ''}:`
          }
          <span className={filterTips ? 'table-filter-tips' : 'filter-tips-hidden'}>
            <span className="iconfont icon icon-gantanhao" />{filterTips}
          </span>
        </Title>
      </Header>
      <Body>
        {/* <RadioRender
          defalutRadio={defalutRadioVal}
        /> */}
        {Object.values(filterItemList).map(value => {
          const { key } = value;
          return (
            <FilterItem
              key={getRandom()}
              itemKey={key}
              afterFilterItemList={afterFilterItemList}
              filterFactors={filterFactors}
              filterItemList={filterItemList}
              factorList={factorList}
              columns={columns}
              tableScope={tableScope}
              currentTable={currentTable}
              handleHideLocation = {handleHideLocation}
              clearLocationResult = {clearLocationResult}
              setFilterTips = {setFilterTips}
              setFilterItemList={setFilterItemList}
              enterCallBack={enterCallBack}
              lang={lang}
            />
          );
        })}
        {defalutRadioVal!="1"?
        <div className="add-btn-container">
          <div className="add-btn" 
            // fieldid={getSysFieldid('add_btn')} 
            onClick={handleAdd}
          >
            {/* 添加条件 */}
            {`+${lang['publiccomponents-000150']?lang['publiccomponents-000150']:getMultiLangByID('publiccomponents-000150')}`}
          </div>
          {/* 清空 */}
          <NCButton onClick={handleClear} fieldid="clear" >
            {lang['publiccomponents-000151']?lang['publiccomponents-000151']:getMultiLangByID('publiccomponents-000151')}
            </NCButton>
        </div>
        :<div/>
      }
      </Body>
      <Footer>
        <NCButtonGroup>
          <NCButton
            className="filter-btn"
            fieldid="filter"
            colors="primary"
            onClick={defalutRadioVal=="1"?handLocationClickPre:handleFilterClick}
          >
            {/* 筛选 */}
            {defalutRadioVal=="1"?(lang['publiccomponents-000157']?lang['publiccomponents-000157']:getMultiLangByID('publiccomponents-000157')):(lang['publiccomponents-000152']?lang['publiccomponents-000152']:getMultiLangByID('publiccomponents-000152'))}
          </NCButton>
          <NCButton className="reset-btn" fieldid="reset" onClick={defalutRadioVal=="1"?handLocationClickNext:handleReset}>
            {/* 重置 */}
            {defalutRadioVal=="1"?(lang['publiccomponents-000158']?lang['publiccomponents-000158']:getMultiLangByID('publiccomponents-000158')):(lang['publiccomponents-000153']?lang['publiccomponents-000153']:getMultiLangByID('publiccomponents-000153'))}
          </NCButton>
        </NCButtonGroup>
        {/* 取消 */}
        <NCButton onClick={defalutRadioVal=="1"?handleHideLocation.bind(null,true,locationResult):handleHide.bind(null, {})} fieldid="cancel" >
          {lang['publiccomponents-000154']?lang['publiccomponents-000154']:getMultiLangByID('publiccomponents-000154')}
          </NCButton>
      </Footer>
    </NCModal>
  );
};

export default FilterPanel;
